﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace ZaxLib.Collections
{
	public class CDataGrid : IDataGrid
	{
		#region Class Parameters

		private ArrayList data;
		//private Dictionary<String, Object>[] data;

		private int rowId;

		#endregion

		#region Constructors

		public CDataGrid()
		{
			Init();
		}

		public void Init()
		{
			rowId = 0;
			data = new ArrayList();
		}

		#endregion

		#region Interface DataGrid

		public void SetCell(String key, Object value)
		{
			// Check if element is already in data structure
			Dictionary<String, Object> row = data[rowId] as Dictionary<String, Object>;
			if (row[key] == null)
			{
				row.Add(key, value);
			}
			else
			{
				row[key] = value;
			}
		}

		public void AddRow()
		{
			Dictionary<String, Object> row = new Dictionary<string, object>();
			AddRow(row);
		}

		public void AddRow(Dictionary<String, Object> row)
		{
			rowId = data.Add(row);
		}

		public Dictionary<String, Object> Row
		{
			get
			{
				Dictionary<String, Object> row = data[rowId] as Dictionary<String, Object>;

				return row;
			}
		}

		public int Count
		{
			get
			{
				return data.Count;
			}
		}

		public int Index
		{
			get
			{
				return rowId;
			}
		}

		#endregion

		#region Interface Rows

		public bool Next()
		{
			bool retVal = rowId + 1 < data.Count;
			// Check if we can go to next row
			if (retVal)
			{
				rowId++;
			}

			// Return if next row was selected
			return retVal;
		}// End method Next

		public bool Previous()
		{
			bool retVal = rowId - 1 >= 0;
			// Check if we can go to previous row
			if (retVal)
			{
				rowId--;
			}

			// Return if previous row was selected
			return retVal;
		}// End method Previous

		public bool Start()
		{
			rowId = -1;
			return data.Count > rowId;
		}// End method Start

		public bool End()
		{
			rowId = data.Count - 1;
			return rowId >= 0;
		}// End method End

		private ArrayList _head = null;
		public ArrayList Head
		{
			get
			{
				if (_head == null)
				{
					_head = new ArrayList();
					foreach (String key in Row.Keys)
					{
						_head.Add(key);
					}
				}
				else
				{
					String cKey = _head[0] as String;
					if (Row[cKey] == null)
					{
						_head = new ArrayList();
						foreach (String key in Row.Keys)
						{
							_head.Add(key);
						}
					}
				}

				return _head;
			}
		}// End parameter HEad


		#endregion

		#region Interface Cell

		public Object GetCell(String key)
		{
			return Row[key];
		}

		#endregion

		#region IEnumerator

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new DataGridEnumerator(this);
		}

		#endregion

	}
}
